package com.hdd.hll.quartz.jobbuilder;

import com.alibaba.fastjson.JSON;
import com.hdd.hll.quartz.entity.JobInfo;
import com.hdd.hll.quartz.entity.TriggerInfo;
import com.hdd.hll.quartz.trigger.CustomTrigger;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * job构建器
 *
 * @author jw
 */
@Component
public class CustomJobBuilder<T> {
    @Autowired
    private Scheduler scheduler;

    @Autowired
    private CustomTrigger customTrigger;

    /**
     * 自定义Job构建 器
     *
     * @param jobInfo job基类实体
     * @param jobClazz 业务job实体 继承自Job类
     * @param jobData 业务数据
     * @return jobDetail实体
     */
    private JobDetail build(JobInfo jobInfo, Class<? extends Job> jobClazz, T jobData) {
        return JobBuilder.newJob(jobClazz)
                // 存储业务数据
                .usingJobData(jobInfo.getName(), JSON.toJSONString(jobData))
                // 每个Job的唯标识
                .withIdentity(jobInfo.getName(), jobInfo.getGroup())
                .build();
    }

    /**
     * 自定义Job注册器
     *
     * @param jobInfo job基类实体
     * @param triggerInfo 触发器基类实体
     * @param jobData 业务数据
     * @param jobClazz 业务job实体 继承自Job类
     * @throws SchedulerException 定时任务注册异常
     */
    public void register(JobInfo jobInfo, TriggerInfo triggerInfo, T jobData, Class<? extends Job> jobClazz) throws SchedulerException {
        scheduler.scheduleJob(build(jobInfo, jobClazz, jobData), customTrigger.build(triggerInfo));
    }
}
